import React, { Component } from "react";
import { connect } from "dva";
import { message, Tabs } from "antd";
import BaseLayout from "@/components/Layout/BaseLayout";
import ExamList from "@/components/ExamList/ExamList";
import ReleaseExam from "./component/ReleaseExam/ReleaseExam";
import ExamInfoAside from "@/components/ExamList/ExamInfoAside";
import StudentStatus from "@/components/ExamList/StudentStatus";
import ExamPaper from "@/components/ExamList/ExamPaper";
import StudentScore from "@/pages/Teacher/component/StudentScore/StudentScore";
import { getExamListByTeachId } from '@/services/exam'
import { getCookie } from "@/utils/cookie/cookie";
import TeachInfo from '@/components/UserInfo/TeachInfo'
import StudentInfoAside from "@/components/ExamList/StudentInfoAside"
import { history } from 'umi'

const { TabPane } = Tabs;
const mapStateToProps = (state) => {
    const { token } = state["token"];
    const { examListTab, configOfShowScore } = state["teacher"];
    const { ws } = state["websocket"]
    return { token, examListTab, configOfShowScore, ws };
};
const mapDispatchToProps = (dispatch) => {
    return {
        changeToExamList() {
            dispatch({
                type: `teacher/changeState`,
                result: { data: "examList" },
                field: "examListTab",
            });
        },
        changeToExamPaper() {
            dispatch({
                type: `teacher/changeState`,
                result: { data: "examPaper" },
                field: "examListTab",
            });
        },
        changeToStudentStatus() {
            dispatch({
                type: `teacher/changeState`,
                result: { data: "studentStatus" },
                field: "examListTab",
            });
        },
        changeToStudentScore() {
            dispatch({
                type: `teacher/changeState`,
                result: { data: "studentScore" },
                field: "examListTab",
            });
        },
        changeExamListTab(examListTab) {
            dispatch({
                type: `teacher/changeState`,
                result: { data: examListTab },
                field: "examListTab",
            });
        },
    };
};

let timer = null
let wsConnetTimer = null

class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            examList: [],
            examListIndex: 0
        };
        this.requestData = this.requestData.bind(this)
    }

    componentDidMount() {
        this.requestData()
        if (getCookie("identity") !== "teacher") {
            message.error("error");
            history.push('/Login')
        }
        timer = setInterval(() => {
            if (getCookie("identity") !== "teacher") {
                message.error("error");
                history.push('/Login')
            }
        }, 500);

        wsConnetTimer = setInterval(() => {
            const { ws } = this.props
            console.log("connect...")
            if (ws instanceof WebSocket) {
                console.log("setOnMessage")
                ws.onmessage = (message) => {
                    const messageData = message.data
                    const { examListStatus } = JSON.parse(messageData)
                    const nextExamList = JSON.parse(JSON.stringify({ data: this.state.examList })).data
                    console.log("update")
                    if (examListStatus instanceof Array) {
                        if (nextExamList instanceof Array) {
                            examListStatus.forEach((data1) => {
                                nextExamList.forEach((data2) => {
                                    if (data1.exam_id === data2.key) {
                                        if (data1.exam_status !== data2.status) {
                                            data2.status = data1.exam_status
                                        }
                                    }
                                })
                            })
                        }
                    }
                    if (nextExamList !== this.state.examList) {
                        this.setState({
                            examList: nextExamList
                        })
                    }
                }
                clearInterval(wsConnetTimer)
                wsConnetTimer = null
            }
        }, 500)
    }

    componentWillUnmount() {
        if (timer) {
            clearInterval(timer)
        }

        const { ws } = this.props
        if (ws instanceof WebSocket) {
            ws.onmessage = () => { }
        }

        if (wsConnetTimer) {
            clearInterval(wsConnetTimer)
            wsConnetTimer = null
        }
    }

    async requestData() {
        // message.loading({
        //     key: 'tip',
        //     content: '加载数据中'
        // })
        const result = await getExamListByTeachId({ teach_id: getCookie("userId") })
        if (result.status === 0) {
            this.setState({
                examList: result.data.map((data) => {
                    return {
                        key: data.exam_id,
                        title: data.exam_title,
                        status: data.exam_status,
                        startTime: data.start_time,
                        endTime: data.end_time,
                        class: data.class_id.split(','),
                        maxScore: data.max_score,
                        passScore: data.pass_score,
                        examPaperId: data.exam_paper_id
                    }
                })
            })
            // message.success({
            //     key: 'tip',
            //     content: '加载完成',
            //     duration: 1
            // })
        } else {
            message.error({
                key: 'tip',
                content: '加载失败',
                duration: 1
            })
        }
    }

    UNSAFE_componentWillReceiveProps(nextProps) {
        if (nextProps.examListTab !== this.props.examListTab) {
            this.requestData()
        }
        return nextProps
    }

    render() {
        const tabPaneMap = {};
        const { examList, examListIndex } = this.state
        tabPaneMap.examList = (
            <TabPane tab="考试列表" key="考试列表">
                <ExamList
                    dataSource={this.state.examList.map((exam, index) => {
                        return {
                            ...exam,
                            onHoverList: [
                                {
                                    show: true,
                                    onClick: () => {
                                        this.setState({
                                            examListIndex: index
                                        }, () => {
                                            this.props.changeToExamPaper()
                                        })
                                    },
                                    text: "查看试卷"
                                },
                                // {
                                //     show: true,//exam.status === "ongoing",
                                //     onClick: () => {
                                //         this.setState({
                                //             examListIndex: index
                                //         }, () => {
                                //             this.props.changeToStudentStatus()
                                //         })
                                //     },
                                //     text: "查看考试"
                                // },
                                {
                                    show: exam.status === "over",
                                    onClick: () => {
                                        this.setState({
                                            examListIndex: index
                                        }, () => {
                                            this.props.changeToStudentScore()
                                        })
                                    },
                                    text: "查看成绩"
                                },
                            ]
                        }
                    })}
                />
            </TabPane>
        );
        tabPaneMap.releaseExam = <TabPane tab="发布考试" key="发布考试">
            <ReleaseExam />
        </TabPane>
        tabPaneMap.studentStatus = <TabPane tab="考试列表" key="考试列表">
            <ExamInfoAside
                onBack={this.props.changeToExamList}
                info={examList[examListIndex]}
                canEdit={examList[examListIndex]?.status}>
                <StudentStatus />
            </ExamInfoAside>
        </TabPane>
        tabPaneMap.examPaper = <TabPane tab="考试列表" key="考试列表">
            <ExamInfoAside onBack={this.props.changeToExamList}
                info={examList[examListIndex]}
                showDel={examList[examListIndex]?.status !== "ongoing"}
                canEdit={examList[examListIndex]?.status}>
                <ExamPaper examPaperId={examList[examListIndex]?.examPaperId} showTrueAnswer={true} showStudentAnswer={false} />
            </ExamInfoAside>
        </TabPane>
        tabPaneMap.teachInfo = <TabPane tab='个人信息' key='个人信息'>
            <TeachInfo />
        </TabPane>
        tabPaneMap.studentScore = <TabPane tab="考试列表" key="考试列表">
            <ExamInfoAside onBack={this.props.changeToExamList}
                info={examList[examListIndex]}
                showBtn={false}
                canEdit={examList[examListIndex]?.status}>
                <StudentScore info={examList[examListIndex]} />
            </ExamInfoAside>
        </TabPane>
        tabPaneMap.studentExamScore = <TabPane tab="考试列表" key="考试列表">
            <StudentInfoAside
                onBack={this.props.changeToExamList}
                info={this.props.configOfShowScore}
                showBtn={false}
                type2={"teacherCheckStudent"}
                canEdit={false}>
                <ExamPaper
                    type={"checkPaper"}
                    type2={"teacherCheckStudent"}
                    info={this.props.configOfShowScore}
                    examPaperId={this.props.configOfShowScore?.examPaperId}
                    showTrueAnswer={true}
                    showStudentAnswer={true}
                />
            </StudentInfoAside>
        </TabPane>

        const tabsPane = [];
        tabsPane.push(tabPaneMap[this.props.examListTab] ? tabPaneMap[this.props.examListTab] : tabPaneMap["examList"]);
        tabsPane.push(tabPaneMap.releaseExam);
        tabsPane.push(tabPaneMap.teachInfo);
        return <BaseLayout title="在线考试·教师" tabsPane={tabsPane} />;
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Index);
